package com.bkitmobile.kesu.android.GUI;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.DatePicker.OnDateChangedListener;
import com.bkitmobile.kesu.android.ClassInfo.RegisterInfo;
import com.bkitmobile.kesu.android.connectServer.Request;
import com.bkitmobile.kesu.android.connectServer.ServiceCallback;
import com.bkitmobile.kesu.android.connectServer.staticClass;

public class SettingProfile extends Activity implements View.OnClickListener{
	
	private TextView tvFName, tvLName, tvSex, tvBday, tvEmail;
	private EditText edFName, edLName, edEmail;
	private DatePicker dpBdate;
	private RadioButton rbMale, rbFemale;
	private Button btnEdit, btnSave, btnReset, btnCancel, btnEditPass,btnChangeAvatar;
	private RegisterInfo ri;
	private Handler handler = new Handler();
	private Dialog editPassDialog;
	View vShow, vEdit;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		init();
	}
	
	private void init() {
		
		getInfo();
		
	}
	
	private void setShowEdit(){
		edFName.setText(ri.getfName());
		edLName.setText(ri.getlName());
		edEmail.setText(ri.getEmail());
		if(ri.getSex().startsWith("m")){
			rbMale.setChecked(true);
			rbFemale.setChecked(false);
		}else{
			rbMale.setChecked(false);
			rbFemale.setChecked(true);
		}
		int date = ri.getDay();
		int month = ri.getMonth();
		int year = ri.getYear();
		int currentYear = (new Date()).getYear() + 1900;
		dpBdate.init(ri.getYear(), ri.getMonth(), ri.getDay(), new OnDateChangedListener() {
			
			@Override
			public void onDateChanged(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				Date now = new Date();
				if(year >= now.getYear() + 1900){
					if(monthOfYear >= now.getMonth()){
						if(dayOfMonth >= now.getDate())
							dpBdate.init(now.getYear()+1900, now.getMonth(), now.getDate(), this);
						else
							dpBdate.init(now.getYear()+1900, now.getMonth(), dayOfMonth, this);
					}
					else
						dpBdate.init(now.getYear()+1900, monthOfYear, dayOfMonth, this);
				}
				else if(year < now.getYear() + 1800)
					dpBdate.init(now.getYear()+1800, monthOfYear, dayOfMonth, this);
			}
		});
	}
	
	private void setTextForTextViews() {
		tvFName.setText(ri.getfName().equals("")?"Need modify":ri.getfName());
		tvLName.setText(ri.getlName().equals("")?"Need modify":ri.getlName());
		tvSex.setText(ri.getSex());
		tvBday.setText(ri.getBDate());
		tvEmail.setText(ri.getEmail().equals("")?"Need modify":ri.getEmail());
		if (currentAvatar != null)
			avatarImg.setImageBitmap(currentAvatar);
	}
	private Bitmap currentAvatar;
	private ImageView imgCurrentAvatar;
	private void getInfo(){
		//define ri here
		String []identities = {"ID"};
		String []atributies = {Request.GET_MY_PROFILE};
		
		Request.sendAndRecieveData(identities, atributies, true,this,new ServiceCallback<String>() {
			
			@Override
			public void onSuccess(final String result) {
				// TODO Auto-generated method stub
				handler.post(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						System.out.println(result);
						JSONObject obj;
						try {
							obj = new JSONObject(result);
							ri = new RegisterInfo();
							ri.setDate(obj.getString("bDay"));
							ri.setEmail(obj.getString("email"));
							ri.setfName(obj.getString("fName"));
							ri.setlName(obj.getString("lName"));
							ri.setSex(obj.getString("sex"));
							try {
								ri.setImg(obj.getString("avatar"));
							} catch (Exception e){
								
							}
							final LayoutInflater i = getLayoutInflater();
							vShow = i.inflate(R.layout.setting_tab_profile1, null);
							tvFName = (TextView) vShow.findViewById(R.id.setting_tab_profile_fname_tv);
							tvLName = (TextView) vShow.findViewById(R.id.setting_tab_profile_lname_tv);
							tvSex = (TextView) vShow.findViewById(R.id.setting_tab_profile_sex);
							tvBday = (TextView) vShow.findViewById(R.id.setting_tab_profile_bdate);
							tvEmail = (TextView) vShow.findViewById(R.id.setting_tab_profile_email_tv);
							vEdit = i.inflate(R.layout.setting_tab_profile2, null);
							edFName = (EditText) vEdit.findViewById(R.id.setting_tab_profile_fname_et);
							edLName = (EditText) vEdit.findViewById(R.id.setting_tab_profile_lname_et);
							edEmail = (EditText) vEdit.findViewById(R.id.setting_tab_profile_email_et);
							imgCurrentAvatar = (ImageView) vShow.findViewById(R.id.setting_current_avatar);
							if (ri.getImg() != null){
								byte[] bytes = Base64.decode(ri.getImg(), Base64.DEFAULT);
								ByteArrayInputStream baos = new ByteArrayInputStream(bytes);
								BitmapDrawable bm = new BitmapDrawable(baos);
								currentAvatar = bm.getBitmap();
							}
							if (currentAvatar != null)
								imgCurrentAvatar.setImageBitmap(currentAvatar);
							rbMale = (RadioButton) vEdit.findViewById(R.id.setting_tab_profile_sex_male);
							rbFemale = (RadioButton) vEdit.findViewById(R.id.setting_tab_profile_sex_female);
							dpBdate = (DatePicker) vEdit.findViewById(R.id.setting_tab_profile_bDate);
							btnEdit = (Button) vShow.findViewById(R.id.setting_tab_profile_edit);
							btnSave = (Button) vEdit.findViewById(R.id.setting_tab_profile_save);
							btnCancel = (Button) vEdit.findViewById(R.id.setting_tab_profile_cancel);
							btnReset = (Button) vEdit.findViewById(R.id.setting_tab_profile_reset);
							btnEditPass = (Button) vEdit.findViewById(R.id.setting_tab_profile_editPass);
							avatarImg = (ImageView) vEdit.findViewById(R.id.setting_avatar);
							setContentView(vShow);
							setTextForTextViews();
							setShowEdit();
							
							btnEdit.setOnClickListener(SettingProfile.this);
							btnSave.setOnClickListener(SettingProfile.this);
							btnReset.setOnClickListener(SettingProfile.this);
							btnEditPass.setOnClickListener(SettingProfile.this);
							btnCancel.setOnClickListener(SettingProfile.this);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}
				});
			}
			
			@Override
			public void onFailure(Exception exception) {
				// TODO Auto-generated method stub
				handler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub

						StaticDialogs.okButtonDialog(SettingProfile.this
								, SettingProfile.this.getString(R.string.disconnect));
					}
				});
			}
		});
		
	}
	private void sendInfo() {
		String request = "<editProfile>"+"<fname>"+ri.getfName()+"<lname>"+ri.getlName()
							+"<sex>"+ri.getSex()+"<bdate>"+ri.getBDate()+"<email>"+ri.getEmail()+"<img>"+ri.getImg();
		staticClass.socket.println(request);
	}
	
	private ImageView avatarImg;
	private static final int MAX_SIZE_IMG = 25;//25kb
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == btnEdit){
			setContentView(vEdit);
			btnChangeAvatar = (Button) findViewById(R.id.setting_avatar_change);
			btnChangeAvatar.setOnClickListener(this);
		} 
		else if (v == btnChangeAvatar){
			try {
				SearchImageDialog dlg = new SearchImageDialog(this){
					@Override
					public void setImage(Bitmap img) {
						// TODO Auto-generated method stub
						avatarImg.setImageBitmap(img);
						SettingProfile.this.currentAvatar = img;
						//resize(avatar);
						try {
							ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
							
							SettingProfile.this.currentAvatar.compress(Bitmap.CompressFormat.PNG, 100, baos);
							byte[] b = baos.toByteArray();
							int size = b.length / 1024;
							if (MAX_SIZE_IMG < size) {
								int scale = MAX_SIZE_IMG *100 / size;
								SettingProfile.this.currentAvatar.compress(Bitmap.CompressFormat.PNG, scale, baos);
								b=baos.toByteArray();
							}
							String avatarString = Base64.encodeToString(b, Base64.DEFAULT);
							ri.setImg(avatarString);
						} catch (Exception e){
							e.printStackTrace();
						}
						//TODO: send request...
						
					}
					
				};
				dlg.show();
			} catch (Exception e){
				e.printStackTrace();
			}
		}
		else if(v == btnSave){
			//TODO: send data
			ri.setfName(edFName.getText().toString());
			ri.setlName(edLName.getText().toString());
			ri.setEmail(edEmail.getText().toString());
			ri.setSex((rbMale.isChecked()?"male":"female"));
			int date = dpBdate.getDayOfMonth();
			int month = dpBdate.getMonth();
			int year = dpBdate.getYear();
			ri.setDate(date, month, year);
			imgCurrentAvatar.setImageBitmap(currentAvatar);
			//send image
			System.out.println(ri.getBDate());
			setTextForTextViews();
			setContentView(vShow);
			sendInfo();
		}
		else if(v == btnReset){
			//TODO: reset form
			setShowEdit();
		}
		else if(v == btnCancel){
			setContentView(vShow);
		}
		else if(v == btnEditPass){
			//TODO: show edit pass form
			if(editPassDialog == null)
				editPassDialog = new ChangePassDialog(this);
			editPassDialog.show();
			Toast.makeText(this, "Edit Pass", Toast.LENGTH_SHORT);
		}
		
	}
	
}
